import { judgmentTypes } from './../judgmentType'
const axios = {
  get: function (url, obj) {
    const { params } = obj
    return new Promise((resovle, reject) => {
      let xhr = new XMLHttpRequest()
      if (params) {
        for (let i in params) {
          url += '?' + i + '=' + params[i]
        }
      }
      xhr.open('get', url, false)
      xhr.send()
      if (xhr.readyState === 4 && xhr.status === 200) {
        let res = JSON.parse(xhr.responseText)
        if (res.code === 200) {
          resovle(res)
        } else {
          reject(res.msg)
        }
      }
    })
  },
  post: function (url, data) {
    return new Promise((resovle, reject) => {
      let xhr = new XMLHttpRequest()
      xhr.open('post', url, false)
      xhr.setRequestHeader('Content-Type', 'application/json')
      xhr.send(JSON.stringify(data))
      if (xhr.readyState === 4 && xhr.status === 200) {
        let res = JSON.parse(xhr.responseText)
        if (res.code === 200) {
          resovle(res)
        } else {
          reject(res.msg)
        }
      }
    })
  },
  create: function (options) {
    let { baseUrl, method, timeout, headers, data } = options
    headers = headers ? headers : 'application/json'
    timeout = timeout ? timeout : 5000
    if (!baseUrl) {
      return new Error('url不能为空')
    }

    return new Promise((resovle, reject) => {
      const xhr = new XMLHttpRequest()
      if (method === 'post') {
        xhr.open('post', baseUrl, false)
        xhr.setRequestHeader('Content-Type', headers)
        xhr.send(JSON.stringify(data))
        if (xhr.readyState === 4 && xhr.status === 200) {
          let res = JSON.parse(xhr.responseText)

          if (res.code === 200) {
            resovle(res)
          } else {
            reject(res.msg)
          }
        }
      } else {
        xhr.open('get', baseUrl, false)
        if (data) {
          for (let i in data) {
            baseUrl += '?' + i + '=' + data[i]
          }
          if (xhr.readyState === 4 && xhr.status === 200) {
            let res = JSON.parse(xhr.responseText)
            if (res.code === 200) {
              resovle(res)
            } else {
              reject(res.msg)
            }
            xhr.send()
          }
        }

        let timer = null
        timer = setTimeout(() => {
          xhr.abort()
          timer = null
          return new Error('超时了')
        }, timeout)
      }
    })
  }
}

export default axios
